import React, { useState, useEffect } from 'react';
import { Form, Input, Radio, Select, Alert, Spin } from 'antd';
const { Option } = Select;
import { useNavigate } from 'react-router-dom';
import { useRegister } from '@/hooks/useLogin';
import { CustomButton } from '@/components/CustomButton';

const SignUpTable = ({ data }) => {

  const navigate = useNavigate();

  const [form] = Form.useForm();
  const { register, response, error, isOk, isLoading: isSigning } = useRegister();
  const [ProvinceData, setProvinceData] = useState([]);
  const [selectedProvince, setSelectedProvince] = useState(null);

  const handleFormSubmission = async () => {
    const formValues = await form.validateFields();
    register(formValues);
  };

  useEffect(() => {
    fetch('/api/data/province')
      .then(response => response.json())
      .then(data => {
        const transformedData = data.result.map(area => ({
          value: area.prov_id,
          label: area.prov_name,
        }));
        setProvinceData(transformedData);
      })
  }, []);


  const handleChange = (value) => {
    setSelectedProvince(value);
  };

  useEffect(() => {
    if (!isSigning && response && isOk && response.detail) {
      setTimeout(() => {
        navigate('/login');
      }, 1000);
    }
  }, [isSigning, response, isOk]);


  return (
    <Spin spinning={isSigning}>

      <Form
        form={form}
        name="dynamic_form"
        onFinish={handleFormSubmission}
        layout='vertical'
        className="p-4 md:p-8"
      >
        {data.map((section, sectionIndex) => (
          <div key={sectionIndex} className="mb-8">
            <h2 className="text-xl mb-4">{section.title}</h2>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-8">
              {section.questions.map((question, questionIndex) => (
                <div key={questionIndex}>
                  {question.type === 'TextInput' && (
                    <Form.Item
                      label={question.label}
                      className='w-full'
                      name={question.name}
                      required={question.required}
                      rules={[{ required: question.required, message: '此字段为必填字段！' }]}
                    >
                      <Input placeholder={question.placeholder} className="rounded-md" />
                    </Form.Item>
                  )}
                  {question.type === 'PhoneInput' && (
                    <Form.Item
                      name="phone_number"
                      label="手机号码："
                      rules={[
                        {
                          required: true,
                          message: '请输入您的电话号码！',
                        },
                        {
                          pattern: /^1[3-9]\d{9}$/,
                          message: '请输入有效的电话号码！',
                        }
                      ]}
                      hasFeedback
                    >
                      <Input />
                    </Form.Item>
                  )}
                  {question.type === 'email' && (
                    <Form.Item
                      name="email"
                      label="电子邮件："
                      rules={[
                        {
                          type: 'email',
                          message: '输入的电子邮件无效！',
                        }
                      ]}
                    >
                      <Input />
                    </Form.Item>
                  )}
                  {question.type === 'Password' && (
                    <Form.Item
                      name="password"
                      label="密码："
                      rules={[
                        {
                          required: true,
                          message: '请输入您的密码！',
                        },
                        {
                          pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\W_]{8,}$/,
                          message: '密码必须至少包含8个字符，并且同时包含字母和数字！',
                        },
                      ]}
                      hasFeedback
                    >
                      <Input.Password />
                    </Form.Item>
                  )}
                  {question.type === 'PasswordConfirm' &&
                    <Form.Item
                      name="confirm"
                      label="确认密码："
                      dependencies={['Password']}
                      hasFeedback
                      rules={[
                        {
                          required: true,
                          message: '请确认您的密码！',
                        },
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error('您输入的新密码不匹配！'));
                          },
                        }),
                      ]}
                    >
                      <Input.Password />
                    </Form.Item>
                  }
                  {
                    question.type === 'RadioGroup' && (
                      <>
                        <Form.Item
                          label={question.label}
                          name={question.name}
                          required={question.required}
                          rules={[{ required: question.required, message: '此字段为必填字段！' }]}
                        >
                          <Radio.Group
                            options={question.options}
                          />
                        </Form.Item>
                      </>
                    )
                  }
                  {
                    question.type === 'ProvinceSelector' && (
                      <Form.Item
                        label={question.label}
                        className='w-full'
                        name={question.name}
                        required={question.required}
                        rules={[{ required: question.required, message: '此字段为必填字段！' }]}
                      >
                        <Select
                          showSearch
                          style={{ width: '100%' }}
                          allowClear
                          onChange={handleChange}
                          optionFilterProp="children"
                          filterOption={(input, option) =>
                            option.children.indexOf(input) >= 0
                          }
                        >
                          {ProvinceData.map(province => (
                            <Option key={province.value} value={province.value}>
                              {province.label}
                            </Option>
                          ))}
                        </Select>
                      </Form.Item>
                    )
                  }
                </div>
              ))}
            </div>
          </div>
        ))
        }

        <>
          <CustomButton type="submit" className="w-full rounded-lg text-sm font-semibold  bg-sky-700 text-white hover:bg-sky-600 sm:w-1/2 sm:mx-[12rem] focus:outline-none focus:ring-2 focus:ring-sky-500">
            Submit
          </CustomButton>
          {
            !isSigning && response && isOk && response.detail && <Alert message={response.detail} type='success' className='mt-4  text-center text-green'></Alert>
          }
          {
            !isSigning && response && !isOk && response.detail && <Alert message={response.detail} type='error' className='mt-6 text-center text-red-600'></Alert>
          }
        </>
      </Form >
    </Spin>
  );
};
export default SignUpTable;
